package com.yunke.controller.user;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunke.common.result.YunkeResult;
import com.yunke.entity.YunkeFile;
import com.yunke.service.YunkeFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户端文件管理控制器
 * 
 * @author yunke
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/user/file")
@RequiredArgsConstructor
@Tag(name = "用户端文件管理", description = "用户端文件管理相关接口")
public class UserFileController {

    private final YunkeFileService yunkeFileService;

    @PostMapping("/upload")
    @Operation(summary = "上传文件")
    public YunkeResult<YunkeFile> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(required = false) String fileCategory,
            @RequestParam(required = false) String businessType,
            @RequestParam(required = false) Long businessId) {
        try {
            YunkeFile yunkeFile = yunkeFileService.uploadFile(file, fileCategory, businessType, businessId);
            return YunkeResult.success(yunkeFile);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return YunkeResult.error("文件上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/upload/batch")
    @Operation(summary = "批量上传文件")
    public YunkeResult<List<YunkeFile>> uploadFiles(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam(required = false) String fileCategory,
            @RequestParam(required = false) String businessType,
            @RequestParam(required = false) Long businessId) {
        try {
            List<YunkeFile> yunkeFiles = yunkeFileService.uploadFiles(files, fileCategory, businessType, businessId);
            return YunkeResult.success(yunkeFiles);
        } catch (Exception e) {
            log.error("批量文件上传失败", e);
            return YunkeResult.error("批量文件上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询文件列表")
    public YunkeResult<IPage<YunkeFile>> getFilePage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer fileType,
            @RequestParam(required = false) String fileCategory,
            @RequestParam(required = false) String businessType) {
        // TODO: 从当前登录用户获取userId
        Long userId = 1L;
        IPage<YunkeFile> page = yunkeFileService.getFilePage(current, size, fileType, fileCategory, businessType, userId);
        return YunkeResult.success(page);
    }

    @GetMapping("/list")
    @Operation(summary = "查询我的文件列表")
    public YunkeResult<List<YunkeFile>> getMyFiles(
            @RequestParam(required = false) Integer fileType,
            @RequestParam(required = false) String fileCategory) {
        // TODO: 从当前登录用户获取userId
        Long userId = 1L;
        List<YunkeFile> files = yunkeFileService.getFilesByUser(userId, fileType, fileCategory);
        return YunkeResult.success(files);
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "查询文件详情")
    public YunkeResult<YunkeFile> getFileDetail(@PathVariable Long id) {
        YunkeFile file = yunkeFileService.getFileById(id);
        if (file == null) {
            return YunkeResult.error("文件不存在");
        }
        // 增加访问次数
        yunkeFileService.increaseAccessCount(id);
        return YunkeResult.success(file);
    }

    @GetMapping("/download/{id}")
    @Operation(summary = "获取下载链接")
    public YunkeResult<String> getDownloadUrl(@PathVariable Long id) {
        // TODO: 从当前登录用户获取userId
        Long userId = 1L;
        String downloadUrl = yunkeFileService.getDownloadUrl(id, userId);
        if (downloadUrl == null) {
            return YunkeResult.error("文件不存在或无权限");
        }
        // 增加下载次数
        yunkeFileService.increaseDownloadCount(id);
        return YunkeResult.success(downloadUrl);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除文件")
    public YunkeResult<String> deleteFile(@PathVariable Long id) {
        // TODO: 从当前登录用户获取userId
        Long userId = 1L;
        boolean success = yunkeFileService.deleteFile(id, userId);
        if (success) {
            return YunkeResult.success("删除成功");
        } else {
            return YunkeResult.error("删除失败");
        }
    }

    @PostMapping("/delete/batch")
    @Operation(summary = "批量删除文件")
    public YunkeResult<String> deleteFiles(@RequestBody List<Long> ids) {
        // TODO: 从当前登录用户获取userId
        Long userId = 1L;
        boolean success = yunkeFileService.deleteFiles(ids, userId);
        if (success) {
            return YunkeResult.success("批量删除成功");
        } else {
            return YunkeResult.error("批量删除失败");
        }
    }

    @GetMapping("/categories")
    @Operation(summary = "查询所有分类")
    public YunkeResult<List<String>> getAllCategories() {
        List<String> categories = yunkeFileService.getAllCategories();
        return YunkeResult.success(categories);
    }

    @PutMapping("/move/{id}")
    @Operation(summary = "移动文件分类")
    public YunkeResult<String> moveCategory(
            @PathVariable Long id,
            @RequestParam String newCategory) {
        // TODO: 从当前登录用户获取userId
        Long userId = 1L;
        boolean success = yunkeFileService.moveCategory(id, newCategory, userId);
        if (success) {
            return YunkeResult.success("移动成功");
        } else {
            return YunkeResult.error("移动失败");
        }
    }

    @GetMapping("/statistics")
    @Operation(summary = "查询文件统计信息")
    public YunkeResult<Map<String, Object>> getFileStatistics(
            @RequestParam(required = false) Integer fileType,
            @RequestParam(required = false) String fileCategory) {
        // TODO: 从当前登录用户获取userId
        Long userId = 1L;
        long totalSize = yunkeFileService.getTotalSize(userId, fileType, fileCategory);
        long fileCount = yunkeFileService.countFiles(userId, fileType, fileCategory);
        
        // 构造返回数据
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalSize", totalSize);
        statistics.put("fileCount", fileCount);
        statistics.put("totalSizeText", formatFileSize(totalSize));
        
        return YunkeResult.success(statistics);
    }

    /**
     * 格式化文件大小
     */
    private String formatFileSize(long size) {
        if (size < 1024) {
            return size + " B";
        } else if (size < 1024 * 1024) {
            return String.format("%.2f KB", size / 1024.0);
        } else if (size < 1024 * 1024 * 1024) {
            return String.format("%.2f MB", size / (1024.0 * 1024));
        } else {
            return String.format("%.2f GB", size / (1024.0 * 1024 * 1024));
        }
    }
} 